<template>
  <a-modal
    :open="open"
    :title="title"
    @update:open="(val) => $emit('update:open', val)"
    @ok="handleOk"
  >
    <a-form
      ref="formRef"
      style="margin-top: 20px"
      layout="vertical"
      :model="localFormState"
      :rules="rules"
    >
      <a-form-item label="用户名称" name="name">
        <a-input v-model:value="localFormState.name" placeholder="请输入用户名称" allow-clear />
      </a-form-item>
      <a-form-item label="真实姓名" name="realName">
        <a-input v-model:value="localFormState.realName" placeholder="请输入真实姓名" allow-clear />
      </a-form-item>
      <a-form-item label="登录密码" name="password">
        <a-input-password
          v-model:value="localFormState.password"
          placeholder="请输入登录密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="再次确认密码" name="passwordAgain">
        <a-input-password
          v-model:value="localFormState.passwordAgain"
          placeholder="请输入登录密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="所属组织" name="subordinate">
        <a-select
          v-model:value="localFormState.subordinate"
          show-search
          :filter-option="filterOption"
          placeholder="请选择所属组织"
          allow-clear
          :options="options1"
        >
        </a-select>
      </a-form-item>
      <a-form-item label="角色名称" name="role">
        <a-select
          v-model:value="localFormState.role"
          mode="multiple"
          show-search
          :filter-option="filterOption"
          placeholder="请选择角色名称"
          allow-clear
          :options="options2"
        >
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { useUserForm } from './useUserForm.ts'
import { filterOption } from '@/utils/selectOptions.ts'

interface FormState {
  name: string
  realName: string
  password: string
  passwordAgain: string
  subordinate: string
  role: string[]
}

interface Option {
  value: string
  label: string
}

const props = defineProps<{
  open: boolean
  title: string
  formState: FormState
}>()

const emit = defineEmits(['update:open', 'submit', 'update:formState'])

const { formRef, rules, options1, options2 } = useUserForm()

const localFormState = computed({
  get: () => props.formState,
  set: (val) => emit('update:formState', val),
})

watch(
  () => props.formState,
  (newVal) => {
    emit('update:formState', newVal)
  },
  { deep: true },
)

const handleOk = () => {
  emit('submit')
}
</script>
